// 路由守卫
// 1、守卫 uni.navigateTo
import { confimMenuExist } from "./fun";
import { whiteList, page404, urlMapping } from "./map-url";

const useWeChatLoginAuthority = false

uni.addInterceptor('navigateTo', {
    // before
    invoke(args) {
        if (useWeChatLoginAuthority) {
            return invoke(args)
        }
    },
    success(args) {
        // console.log('interceptor-success', args)
    },
    fail(err) {
        // console.log('interceptor-fail',err)
    },
    complete(res) {
        // console.log('interceptor-complete',res)
    }
})
// 2、守卫 uni.switchTab
uni.addInterceptor('switchTab', {
    invoke(args) {
        if (useWeChatLoginAuthority) {
            return invoke(args)
        }
        // console.log('interceptor-invoke', args)
    },
    success(args) {
        // console.log('interceptor-success', args)
    },
    fail(err) {
        // console.log('interceptor-fail',err)
    },
    complete(res) {
        // console.log('interceptor-complete',res)
    }
})

function invoke(args) {
    // 权限不符合跳转到404
    let url = args.url
    // 去除url参数
    if (url && url.indexOf('?') >= 0) {
        url = (url.split('?') || [])[0] || ''
    }
    const menuList = uni.getStorageSync('menuList')
    if (whiteList.find(x => x === url)) {
        // 白名单
        return true
    } else if (page404.find(x => x === url)) {
        // 404 页面
        return true
    } else {
        let web_url = urlMapping('uni', url)
        web_url = (menuList.find(x => x.path === web_url) || {}).path
        // 有权限
        if (web_url) {
            return true
        } else {
            uni.showToast({
            	title:'该账户没有权限',
            	icon:'none'
            })
            return false
        }
    }
}
